package com.yami.shop.api.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.dto.SignInReceiveDto;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.SendUserDropsParam;
import com.yami.shop.bean.param.UserUpdateParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.StringUtils;
import com.yami.shop.rights.common.dto.ProdRightsDto;
import com.yami.shop.rights.common.model.RightsExternal;
import com.yami.shop.rights.common.service.RightsExternalService;
import com.yami.shop.security.common.service.AppConnectService;
import com.yami.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@RestController
@Tag(name = "签到领取")
@RequestMapping("/signInReceive")
public class MeetingSignReceiveController {

    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProdNftService prodNftService;
    @Autowired
    private ChannelUserRelationRecordService channelUserRelationRecordService;
    @Autowired
    private BusinessNftService businessNftService;
    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private MeetingSignReceiveService meetingSignReceiveService;

    @Autowired
    private UserCancelService userCancelService;

    @Autowired
    private AppConnectService appConnectService;

    @Autowired
    private MeetingSignService meetingSignService;

    @Autowired
    private MeetingService meetingService;
    @Autowired
    private RightsExternalService rightsExternalService;

    @PostMapping("/receive")
    @Operation(summary = "领取")
    @Transactional
    public ServerResponseEntity receive(@RequestBody SignInReceiveDto signInReceiveDto) {
        User user = userService.getUserByUserId(signInReceiveDto.getUserId());
        if (StringUtils.isEmpty(user.getIdNumber()) || StringUtils.isEmpty(user.getRealName())) {
            throw new YamiShopBindException("请先实名认证！");
        }
        Product productByProdId = productService.getProductByProdId(signInReceiveDto.getProdId());
        if (productByProdId == null) {
            return ServerResponseEntity.showFailMsg("商品不存在");
        }
        long count = meetingSignReceiveService.count(new LambdaQueryWrapper<MeetingSignReceive>().eq(MeetingSignReceive::getUserId, signInReceiveDto.getUserId()).eq(MeetingSignReceive::getMeetingId, signInReceiveDto.getMeetingId()).eq(MeetingSignReceive::getProdId, signInReceiveDto.getProdId()));
        if (count > 0) {
            return ServerResponseEntity.showFailMsg("已经领取过了");
        }
        if (!channelUserRelationRecordService.isHasDTCAddress(signInReceiveDto.getUserId(), productByProdId.getChain(), productByProdId.getChannelCode())) {
            channelUserRelationRecordService.createDtcAddress(signInReceiveDto.getUserId(), productByProdId.getChain(), productByProdId.getChannelCode());
        }
        Meeting byId = meetingService.getById(signInReceiveDto.getMeetingId());
        if(byId.getMeetingStatus()==0){
            return ServerResponseEntity.showFailMsg("会议已经失效了");
        }
        MeetingSignReceive meetingSignReceive = new MeetingSignReceive();
        meetingSignReceive.setMeetingId(signInReceiveDto.getMeetingId());
        meetingSignReceive.setCreateTime(new Date());
        meetingSignReceive.setProdId(signInReceiveDto.getProdId());
        meetingSignReceive.setUserId(signInReceiveDto.getUserId());
        meetingSignReceiveService.save(meetingSignReceive);
        //2 任务空投逻辑
        UserUpdateParam param = new UserUpdateParam();
        // 商品信息
        List<SendUserDropsParam> userDropsParams = new ArrayList<>();
        SendUserDropsParam sendUserDropsParam = new SendUserDropsParam();
        sendUserDropsParam.setTargetId(signInReceiveDto.getProdId());
        sendUserDropsParam.setType(0);
        sendUserDropsParam.setNums(1);
        userDropsParams.add(sendUserDropsParam);
        param.setDrops(userDropsParams);
        param.setUserIds(Collections.singletonList(signInReceiveDto.getUserId()));
        param.setBusinessType(2);
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(productByProdId.getShopId());
        businessNftService.bindDropById(param, shopDetail);
        return ServerResponseEntity.success();
    }

    @PostMapping("/signIn")
    @Operation(summary = "会议签到", description = "会议签到")
    public ServerResponseEntity<MeetingSign> save(@RequestBody @Valid MeetingSign meetingSign) {
        Meeting byId = meetingService.getById(meetingSign.getMeetingId());
        if(byId.getMeetingStatus()==0){
            return ServerResponseEntity.showFailMsg("会议已经失效了");
        }
        meetingSign.setCreateTime(new Date());
        //使用名称和号码同时条件判断，可能出现同系统用户不同签到人名，重复签到
        long count = meetingSignService.count(new LambdaQueryWrapper<MeetingSign>().eq(MeetingSign::getMeetingId, meetingSign.getMeetingId()).eq(MeetingSign::getTelephone, meetingSign.getTelephone()));
        if (count > 0) {
            // 已签到，不能再进行新增操作
            throw new YamiShopBindException("已签到,请勿重复签到！");
        }
        // 注册用户
        // 正在进行申请注册
        if (userService.count(new LambdaQueryWrapper<User>().eq(User::getUserMobile, meetingSign.getTelephone())) == 0) {
            // 判断注销时间
            Boolean conformToRegister = userCancelService.isConformToRegister(meetingSign.getTelephone(), "");
            if (!conformToRegister) {
                return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.user.check.date"));
            }
            User user = appConnectService.registerAndBindUser(meetingSign.getTelephone(), null, null);
            meetingSign.setUser(user);
            meetingSign.setUserId(user.getUserId());
        } else {
            User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserMobile, meetingSign.getTelephone()));
            meetingSign.setUserId(user.getUserId());
            meetingSign.setUser(user);
        }
        meetingSignService.save(meetingSign);
        return ServerResponseEntity.success(meetingSign);
    }


    @GetMapping("/isSignIn")
    @Operation(summary = "根据手机号姓名查询是否有签到信息", description = "根据手机号姓名查询是否有签到信息")
    public ServerResponseEntity<MeetingSign> isSignIn(@RequestParam("meetingId") String meetingId,
                                                      @RequestParam("name") String name,
                                                      @RequestParam("telephone") String telephone) {
        MeetingSign meetingSign = meetingSignService.getOne(new LambdaQueryWrapper<MeetingSign>().eq(MeetingSign::getMeetingId, meetingId).eq(MeetingSign::getParticipants, name).eq(MeetingSign::getTelephone, telephone));
        if (ObjectUtil.isNotNull(meetingSign)) {
            // 已签到，返回签到信息
            User user = userService.getUserByUserId(meetingSign.getUserId());
            meetingSign.setUser(user);
            //判断是否领取
            long count = meetingSignReceiveService.count(new LambdaQueryWrapper<MeetingSignReceive>().eq(MeetingSignReceive::getUserId,meetingSign.getUserId()).eq(MeetingSignReceive::getMeetingId, meetingId));
            meetingSign.setReceive(count>0);
            return ServerResponseEntity.success(meetingSign);
        }
        return ServerResponseEntity.success(null);
    }


    @GetMapping("/meetingIdInfo/{meetingId}")
    @Operation(summary = "根据会议Id获取会议详情", description = "根据会议Id获取会议详情")
    public ServerResponseEntity<Meeting> info(@PathVariable("meetingId") Long meetingId) {
        Meeting meeting = meetingService.getOne(new LambdaQueryWrapper<Meeting>().eq(Meeting::getMeetingId, meetingId));
        return ServerResponseEntity.success(meeting);
    }

    @GetMapping("/getRecordData")
    @Operation(summary = "根据会议ID查询券核销情况", description = "根据会议ID查询券核销情况")
    public ServerResponseEntity<List<RightsExternal>> getRecordData(@RequestParam("meetingId") String meetingId){
        Meeting meeting = meetingService.getById(meetingId);
        if(ObjectUtil.isEmpty(meeting) || ObjectUtil.isEmpty(meeting.getProdId())){
            return ServerResponseEntity.success();
        }
        ProdNft prodNft = prodNftService.getDataByProdId(meeting.getProdId());
        PageParam<RightsExternal> param = new PageParam<>();
        param.setCurrent(1);
        param.setSize(50);
        List<RightsExternal> rightsExternals = rightsExternalService.getDataListByRithsIds(prodNft.getRightsId());
        return ServerResponseEntity.success(rightsExternals);
    }


}
